package com.luoyx.vjsb.captcha.controller;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.luoyx.vjsb.captcha.config.CaptchaProperties;
import com.luoyx.vjsb.captcha.sdk.GeetestLib;
import com.luoyx.vjsb.common.util.IpInfoUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;

/**
 * <p>
 *
 * </p>
 *
 * @author luoyuanxiang <p>luoyuanxiang.github.io</p>
 * @since 2020/4/2 17:36
 */
@Controller
public class GeetestController {

    @Resource
    private CaptchaProperties captchaProperties;

    @Resource
    private IpInfoUtil ipInfoUtil;

    @RequestMapping("startCaptcha")
    public void startCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (CaptchaProperties.G_TYPE.equals(request.getParameter("g_type"))) {
            // 腾讯验证
            tencentCaptcha(request, response);
        } else {
            // 极验验证码
            geetestCaptcha(request, response);
        }
    }

    /**
     * 腾讯验证码
     *
     * @param request  1
     * @param response 1
     * @throws IOException 1
     */
    private void tencentCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String s = HttpUtil.get(String.format(captchaProperties.getTencentVerifyUri(), captchaProperties.getTencentAppId(),
                captchaProperties.getTencentAppSecret(),
                URLEncoder.encode(request.getParameter("ticket"), "UTF-8"),
                URLEncoder.encode(request.getParameter("randstr"), "UTF-8"),
                URLEncoder.encode(ipInfoUtil.getIpAddr(request), "UTF-8")));

        cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(s);
        int code = Integer.parseInt(jsonObject.get("response").toString());
        if (code == 1) {
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("code", 1);
            jsonObject1.put("msg", "验证成功");
            react(response, jsonObject1);
        }
    }

    /**
     * 极验验证码
     *
     * @param request  1
     * @param response 1
     * @throws IOException 1
     */
    private void geetestCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        GeetestLib gtSdk = new GeetestLib(captchaProperties.getGeetestId(), captchaProperties.getGeetestKey(),
                captchaProperties.getNewFailback());

        String resStr;

        String userid = "test";

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<>(3);
        //网站用户id
        param.put("user_id", userid);
        //web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
        param.put("client_type", "web");
        //传输用户请求验证时所携带的IP
        param.put("ip_address", ipInfoUtil.getIpAddr(request));

        gtSdk.preProcess(param);

        resStr = gtSdk.getResponseStr();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 1);
        jsonObject.put("msg", "验证成功");
        jsonObject.put("data", JSONUtil.parseObj(resStr));
        react(response, jsonObject);
    }

    private void react(HttpServletResponse response, JSONObject out) throws IOException {
        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.println(out);
    }
}
